
#include <GL/gl.h>
#include <math.h>
#include "sphere.h"



void drawTexturedSphere (const float radix, const int slices, const int stacks) {
	
	const float PI = 3.141592654;
	
	if (radix <= 0.0f || stacks <= 1 || slices <= 2) {
		return;
	}

	float r = fabs(radix);
	
	float theta = 0.0f;
	float phi = 0.0f; 
	int i, j;
	float thetaInc = PI / stacks;
	float phiInc = 2.0 * PI / slices;
	float x, y, z, s, t, nx, ny, nz;
	
	//Polo norte con un cap
	glBegin(GL_TRIANGLE_FAN);

		s = 0.5;
		t = 1.0;
		glTexCoord2f(s, t);

		nx = sin(theta) * cos(phi);
		ny = sin(theta) * sin(phi);
		nz = cos(theta);
		glNormal3f(nx, ny, nz);

		x = r * sin(theta) * cos(phi);
		y = r * sin(theta) * sin(phi);
		z = r * cos(theta);
		glVertex3f(x, y, z);

		theta = thetaInc;
		
		for (i = 0; i <= slices; i++) {

			s = phi / (2.0 * PI);
			t = (1.0 - (theta / PI));
			glTexCoord2f(s, t);

			nx = sin(theta) * cos(phi);
			ny = sin(theta) * sin(phi);
			nz = cos(theta);
			glNormal3f(nx, ny, nz);

			x = r * sin(theta) * cos(phi);
			y = r * sin(theta) * sin(phi);
			z = r * cos(theta);
			glVertex3f(x, y, z);

			phi += phiInc;	
		}
	glEnd();
	
	//Trazamos la parte central
	for (i = 1; i < (stacks - 1); i++) {
		phi = 0.0;
		glBegin(GL_QUAD_STRIP);
		for (j = 0; j <= slices; j++) {
			s = phi / (2.0 * PI);
			t = 1.0 - (theta / PI);
			glTexCoord2f(s, t);

			nx = sin(theta) * cos(phi);
			ny = sin(theta) * sin(phi);
			nz = cos(theta);
			glNormal3f(nx, ny, nz);

			x = r * sin(theta) * cos(phi);
			y = r * sin(theta) * sin(phi);
			z = r * cos(theta);
			glVertex3f(x, y, z);

			s = phi / (2.0 * PI);
			t = 1.0 - ((theta + thetaInc) / PI);
			glTexCoord2f(s, t);

			nx = sin(theta + thetaInc) * cos(phi);
			ny = sin(theta + thetaInc) * sin(phi);
			nz = cos(theta + thetaInc);
			glNormal3f(nx, ny, nz);

			x = r * sin(theta + thetaInc) * cos(phi);
			y = r * sin(theta + thetaInc) * sin(phi);
			z = r * cos(theta + thetaInc);
			glVertex3f(x, y, z);

			phi += phiInc;	
		}
		glEnd();
		theta += thetaInc;
	}
		
	
	//Trazamos el Polo sur con su cap 
	phi = 2.0 * PI;
	glBegin(GL_TRIANGLE_FAN);
		s = 0.5;
		t = 0.0;
		glTexCoord2f(s, t);

		nx = sin(PI) * cos(0.0);
		ny = sin(PI) * sin(0.0);
		nz = cos(PI);
		glNormal3f(nx, ny, nz);

		x = r * sin(PI) * cos(0.0);
		y = r * sin(PI) * sin(0.0);
		z = r * cos(PI);
		glVertex3f(x, y, z);
		
		for (i = 0; i <= slices; i++) {
			s = phi / (2.0 * PI);
			t = 1.0 - (theta / PI);
			glTexCoord2f(s, t);

			nx = sin(theta) * cos(phi);
			ny = sin(theta) * sin(phi);
			nz = cos(theta);
			glNormal3f(nx, ny, nz);

			x = radix * sin(theta) * cos(phi);
			y = radix * sin(theta) * sin(phi);
			z = radix * cos(theta);
			glVertex3f(x, y, z);

			phi -= phiInc;
		}
	glEnd();	
	
	return;
}
